package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BusinessException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void remove(Long id) {
        //查看当前分类是否关联菜品,若关联则抛出异常
        LambdaQueryWrapper<Dish> dishLqw = new LambdaQueryWrapper<>();
        dishLqw.eq(Dish::getCategoryId,id);
        int dishCount = dishService.count(dishLqw);
        if(dishCount > 0){
            //关联菜品,抛出异常
            throw new BusinessException("当前分类存在关联菜品,不可删除");
        }
        //查看当前分类是否关联套餐,若关联则抛出异常
        LambdaQueryWrapper<Setmeal> setmealLqw = new LambdaQueryWrapper<>();
        setmealLqw.eq(Setmeal::getCategoryId,id);
        int setmealCount = setmealService.count(setmealLqw);
        if(setmealCount > 0){
            //关联套餐,抛出异常
            throw new BusinessException("当前分类存在关联套餐,不可删除");
        }
        //没有关联,执行删除
        super.removeById(id);
    }
}
